package top.continew.admin.webapi.sport;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.validation.annotation.Validated;
import top.continew.admin.common.enums.GenderEnum;
import top.continew.admin.common.model.dto.LoginUser;
import top.continew.admin.common.util.helper.LoginHelper;
import top.continew.admin.sport.model.req.ProjectEntryTeamMembersReq;
import top.continew.admin.sport.model.resp.ProjectEntryExcel;
import top.continew.admin.sport.service.ProjectEntryTeamMembersService;
import top.continew.admin.system.model.entity.UserDO;
import top.continew.admin.system.service.UserService;
import top.continew.starter.extension.crud.enums.Api;

import io.swagger.v3.oas.annotations.tags.Tag;

import org.springframework.web.bind.annotation.*;

import top.continew.starter.extension.crud.annotation.CrudRequestMapping;
import top.continew.starter.extension.crud.controller.BaseController;
import top.continew.admin.sport.model.query.ProjectEntryQuery;
import top.continew.admin.sport.model.req.ProjectEntryReq;
import top.continew.admin.sport.model.resp.ProjectEntryDetailResp;
import top.continew.admin.sport.model.resp.ProjectEntryResp;
import top.continew.admin.sport.service.ProjectEntryService;
import top.continew.starter.extension.crud.model.query.PageQuery;
import top.continew.starter.extension.crud.model.query.SortQuery;
import top.continew.starter.extension.crud.model.resp.PageResp;
import top.continew.starter.file.excel.converter.ExcelBigNumberConverter;
import top.continew.starter.web.model.R;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 报名管理 API
 *
 * @author xiahaike
 * @since 2024/09/15 01:27
 */
@Tag(name = "报名管理 API")
@RestController
@CrudRequestMapping(value = "/sport/projectEntry", api = {Api.PAGE, Api.GET, Api.ADD, Api.UPDATE, Api.DELETE, Api.EXPORT})
public class ProjectEntryController extends BaseController<ProjectEntryService, ProjectEntryResp, ProjectEntryDetailResp, ProjectEntryQuery, ProjectEntryReq> {

    @Resource
    private UserService userService;

    @Resource
    private ProjectEntryService projectEntryService;

    @Resource
    private ProjectEntryTeamMembersService projectEntryTeamMembersService;

    @Operation(summary = "分页查询列表", description = "分页查询列表")
    @ResponseBody
    @GetMapping
    @Override
    public R<PageResp<ProjectEntryResp>> page(ProjectEntryQuery projectEntryQuery, @Validated PageQuery pageQuery) {
        this.checkPermission(Api.LIST);
        PageResp<ProjectEntryResp> projectEntryRespPageResp = projectEntryService.myPage(projectEntryQuery, pageQuery);
        return R.ok(projectEntryRespPageResp);
    }

    @ResponseBody
    @GetMapping("/apply/{projectId}/{type}/{gtype}")
    @Operation(summary = "比赛报名", description = "比赛报名")
    public R<String> apply(@PathVariable Long projectId,@PathVariable Integer type, @PathVariable Integer gtype) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        Long userId = loginUser.getId();
        UserDO userDO = userService.getById(userId);
        System.out.println(userDO.toString());
        GenderEnum gender = userDO.getGender();
        if (!gender.getValue().equals(gtype)) {
            return R.fail("请选择正确的组别");
        }
        ProjectEntryReq projectEntryReq = new ProjectEntryReq();
        // 查询是否已经报名
        if (type == 0) {
            // 个人报名
            // 将projectId和userId插入到报名表中
            projectEntryReq.setProjectId(projectId);
            projectEntryReq.setUserId(userId);
            // 查询是否已经报名
            ProjectEntryResp projectEntryResp = projectEntryService.getOneByUserId(projectEntryReq);
            if (projectEntryResp != null) {
                return R.fail("您已经报名，请勿重复报名");
            }
            projectEntryService.add(projectEntryReq);
            return R.ok("报名成功");
        } else if (type == 1) {
            // 团队报名
            // 将projectId和deptId插入到报名表中
            projectEntryReq.setProjectId(projectId);
            projectEntryReq.setTeamId(userDO.getDeptId());
            ProjectEntryResp projectEntryResp = projectEntryService.getOneByTeamId(projectEntryReq);
            ProjectEntryTeamMembersReq projectEntryTeamMembersReq = new ProjectEntryTeamMembersReq();
            projectEntryTeamMembersReq.setProjectId(projectId);
            projectEntryTeamMembersReq.setDeptId(userDO.getDeptId());
            projectEntryTeamMembersReq.setUserId(userId);
            if (projectEntryResp == null) {
                //说明是本团队第一次报名参加此比赛 并将参赛信息插入到sp_project_entry_team_members表中
                projectEntryService.add(projectEntryReq);
                projectEntryTeamMembersService.add(projectEntryTeamMembersReq);
                System.out.println("1111");
                return R.ok("报名成功");
            }
            // 查询project_entry_team_members表中是否已经有该团队的成员报名
            Boolean b = projectEntryTeamMembersService.getOne(projectEntryTeamMembersReq);
            // 如果b为true说明该项目该团队该成员已经报名
            if (b) {
                return R.fail("您已经报名，请勿重复报名");
            } else {
                // 将参赛信息插入到sp_project_entry_team_members表中
                projectEntryTeamMembersService.add(projectEntryTeamMembersReq);
                System.out.println("2222");
                return R.ok("报名成功");
            }
        }
        return R.fail("系统错误，报名失败");
    }

    @Operation(
            summary = "导出数据",
            description = "导出数据"
    )
    @GetMapping({"/export"})
    public void export(ProjectEntryQuery query, SortQuery sortQuery, HttpServletResponse response) {
        this.checkPermission(Api.EXPORT);
        // 查询数据
        List<ProjectEntryExcel> list = projectEntryService.myList(query, sortQuery);
        String projectName = list.get(0).getProjectName();
        String fileName = projectName + ".xlsx";
        response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        try {
            ((ExcelWriterBuilder)((ExcelWriterBuilder) EasyExcelFactory.write(response.getOutputStream(), ProjectEntryExcel.class)
                    .autoCloseStream(false).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()))
                    .registerConverter(new ExcelBigNumberConverter())).sheet(projectName).doWrite(list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}